var phoneExp = /^1\d{10}/; //电话正则匹配
var spaceExp = /^\s*$/; //空格正则匹配

/*打开新窗口
 *id:窗口ID
 *url:路径
 *isNew：false,true,是否打开新窗口
 */

function openLink(obj) {
    openWindow($(obj).attr('data-id'), $(obj).attr('data-href'), true);
}

function openWindow(id, url, isNew) {
    mui.openWindow({
        id: id,
        url: url,
        createNew: isNew
    })
}

//ajax
function ajax(obj, callback) {
    $.ajax({
        type: 'post',
        url: API + obj.url,
        data: obj.data,
        dataType: 'json',
        success: function(res) {
            callback(res)
        },
        error: function(error) {
            console.log(error)
        }

    })
}

//最简单的排序

function sortA(a, b) {
    return a - b;
}
//获取code方法
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = decodeURI(window.location.search).substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//数组比对方法
function diff(arr1, arr2) {
    var newArr = [];
    var arr3 = [];
    for (var i = 0; i < arr1.length; i++) {
        if (arr2.indexOf(arr1[i]) === -1) arr3.push(arr1[i]);
    }
    var arr4 = [];
    for (var j = 0; j < arr2.length; j++) {
        if (arr1.indexOf(arr2[j]) === -1) arr4.push(arr2[j]);
    }
    newArr = arr3.concat(arr4);
    return newArr;
}

function convertCanvasToBlob(canvas) {
    var format = "image/jpeg";
    var base64 = canvas.toDataURL(format);
    var code = window.atob(base64.split(",")[1]);
    var aBuffer = new window.ArrayBuffer(code.length);
    var uBuffer = new window.Uint8Array(aBuffer);
    for (var i = 0; i < code.length; i++) {
        uBuffer[i] = code.charCodeAt(i);
    }
    var Builder = window.WebKitBlobBuilder || window.MozBlobBuilder;
    if (Builder) {
        var builder = new Builder();
        builder.append(buffer);
        return builder.getBlob(format);
    } else {
        return new window.Blob([buffer], { type: format });
    }
}

function getTimeNow() {
    //获取当前时间
    var timeNow = getDate() + ' ' + getTime(true);
    return timeNow;
}

function getDate(countDay) {
    //获取当前日期
    countDay = countDay || 0;
    var date = new Date(),
        month;
    date.setTime(date.getTime() + countDay * 24 * 60 * 60 * 1000);
    var dateArr = [];
    dateArr.push(date.getFullYear());
    dateArr.push(changeSingle(date.getMonth()));
    dateArr.push(changeSingleTime(date.getDate()));
    var timeNow = dateArr.join('-');
    return timeNow;
}

function getTime(format) {
    var date = new Date();
    var timeArr = [];
    timeArr.push(changeSingleTime(date.getHours()));
    timeArr.push(changeSingleTime(date.getMinutes()));
    if (format) {
        timeArr.push('00');
    }
    var timeNow = timeArr.join(':');
    return timeNow;
}

function compress(img, width, height, ratio) {
    var canvas, ctx, img64;

    canvas = document.createElement('canvas');
    canvas.width = width;
    canvas.height = height;

    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);

    img64 = canvas.toDataURL("image/jpeg", ratio);

    return img64;
}

function escapeTime(time) {
    var time = new Date(time);
    var stringArr = [];
    stringArr.push(time.getFullYear());
    stringArr.push(changeSingle(time.getMonth()));
    stringArr.push(changeSingleTime(time.getDate()));
    var timeStr = stringArr.join('-');

    return timeStr;
}

function escapeDateTime(time) {
    var time = new Date(time);
    var stringArr = [];
    stringArr.push(time.getFullYear());

    stringArr.push(changeSingle(time.getMonth()));
    stringArr.push(changeSingleTime(time.getDate()));
    var timeStr = stringArr.join('-');
    var clockArr = [];
    clockArr.push(time.getHours());
    clockArr.push(time.getMinutes());
    clockArr.push('00');
    var clockTring = clockArr.join(':');
    return timeStr + ' ' + clockTring;
}

function changeSingleTime(date) {
    if (date < 9) {
        return '0' + date;
    } else {
        return date;
    }
}

function changeSingle(date) {
    if (date < 9) {
        return '0' + (date + 1);
    } else {
        return date + 1;
    }
}

function convertBase64UrlToBlob(urlData) {
    var arr = urlData.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

function canvasToDataURL(canvas, format, quality) {
    return canvas.toDataURL(format || 'image/jpeg', quality || 0.4);
}

function imageToBlob(src, cb) {
    imageToCanvas(src, function(canvas) {
        cb(convertBase64UrlToBlob(canvasToDataURL(canvas)));
    });
}

function imageToCanvas(src, cb) {
    /* 图片转base64 */
    var canvas = document.createElement('CANVAS');
    var ctx = canvas.getContext('2d');
    var img = new Image();
    img.src = src;
    img.onload = function() {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
        cb(canvas);
    };
}

function distinct(arr) {
    var len = arr.length;
    arr.sort(function(a, b) {
        //对数组进行排序才能方便比较
        return a.type - b.type;
    });

    function loop(index) {
        if (index >= 1) {
            if (arr[index].type == arr[index - 1].type) {
                arr.splice(index, 1);
            }
            loop(index - 1); //递归loop函数进行去重
        }
    }
    loop(len - 1);

    arr.sort(function(a, b) {
        return b.count - a.count;
    });
    return arr;
};

function isCardNo(card) {
    // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X 
    console.log(card);
    var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    console.log(reg.test(card));
    return reg.test(card);
}

function toTree(data) {
    // 删除 所有 children,以防止多次调用
    data.forEach(function(item) {
        delete item.children;
    });

    // 将数据存储为 以 id 为 KEY 的 map 索引数据列
    var map = {};
    data.forEach(function(item) {
        map[item.id] = item;
    });
    //        console.log(map);

    var val = [];
    data.forEach(function(item) {
        item.text = item.areaName;
        // 以当前遍历项，的pid,去map对象中找到索引的id
        var parent = map[item.parentId];

        // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {

            (parent.children || (parent.children = [])).push(item);
        } else {
            //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
            val.push(item);
        }
    });

    return val;
}

function getCheckBoxRes(className) {
    var rdsObj = document.getElementsByClassName(className);
    var checkVal = new Array();
    console.log(rdsObj);
    for (i = 0; i < rdsObj.length; i++) {
        if (rdsObj[i].checked) {
            checkVal.push(rdsObj[i].value);
        }
    }
    return checkVal;
}

//最简单的检验没有输入和空格

function testSpace(content) {
    if (content.length === 0 || spaceExp.test(content)) {
        return true;
    } else {
        return false;
    }
}


//富文本内容样式清除
function richTest(text) {

    text = text.replace(/(\n)/g, "");
    text = text.replace(/(\t)/g, "");
    text = text.replace(/(\r)/g, "");
    text = text.replace(/<\/?[^>]*>/g, "");
    text = text.replace(/\s*/g, "");
    return text;

}

function getRadio(className) {
    var checkedValue;
    var radioArr = document.getElementsByClassName(className);
    for (var i in radioArr) {
        if (radioArr[i].checked) {
            checkedValue = radioArr[i].value;

            break;
        }
    }

    return checkedValue;
}


function setRadio(className, value) {
    var radioArr = document.getElementsByClassName(className);
    for (var i in radioArr) {
        radioArr[i].checked = false;
        if (radioArr[i].value === value.toString()) {
            radioArr[i].checked = true;
        };
    }
}
//选项卡切换封装类，已编译

var _createClass = function() {
    function defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }
    return function(Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; };
}();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var tabClass = function() {
    function tabClass(tabName) {
        _classCallCheck(this, tabClass);

        this.tabName = tabName;
        this.liArr = document.getElementById(this.tabName).querySelectorAll('li');
        this.tabCardArr = document.getElementsByClassName('tab-card');
        this.line = document.getElementById('line');
    }

    _createClass(tabClass, [{
        key: 'init',
        value: function init() {
            var that = this;
            for (var i = 0; i < that.liArr.length; i++) {
                that.liArr[i].index = i;
                that.liArr[i].onclick = function() {
                    that.moveTab(this.index, this);
                };
            }
        }
    }, {
        key: 'moveTab',
        value: function moveTab(num, obj) {
            var that = this;
            for (var y = 0; y < that.liArr.length; y++) {
                that.liArr[y].className = '';
                that.tabCardArr[y].style.display = 'none';
            }
            var winPx = window.innerWidth / that.liArr.length;
            obj.className = 'active';
            that.line.style.transform = 'translate(' + winPx * num + 'px)';
            that.tabCardArr[num].style.display = 'block';
        }
    }]);

    return tabClass;
}();